package com.nuc.zyt.day04.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName Tickets
 * @Description TODO
 * @Author 耀酱
 * @Date 2023/5/29 20:11
 * @Version 1.0
 */

public class Tickets implements Runnable{

    static int ticket = 1;  // 共享的电影票
    static Object obj = new Object();

    Lock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
//            if(method()){
//                break;
//            }
            lock.lock(); // 手动加锁
            try {
                if (ticket <= 1000) {
                    Thread.sleep(100);
                System.out.println(Thread.currentThread().getName() + "正在售卖第" + ticket + "张票");
                ticket++;
            }else {
                break;
            }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock(); // 无论如何都要执行解锁
            }


        }
    }

//    public synchronized boolean method(){
//        if (ticket <= 100) {
//            System.out.println(Thread.currentThread().getName() + "正在售卖第" + ticket + "张票");
//            ticket++;
//        }else {
//            return true;
//        }
//        return false;
//    }
}
